/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mongoosehome.web.login.action;

import com.mongoosehome.web.base.BaseActon;
import com.mongoosehome.web.common.domain.TMemberRank;
import com.mongoosehome.web.common.domain.TRole;
import com.mongoosehome.web.common.domain.TUser;
import com.mongoosehome.web.common.utils.EncodeUtils;
import com.mongoosehome.web.login.service.MemberRankService;
import com.mongoosehome.web.login.service.UserService;
import com.opensymphony.xwork2.ModelDriven;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.SessionMap;
import org.json.JSONObject;

/**
 *
 * @author Administrator
 * linjie 
 * 注册action 
 */
public class UserAction extends BaseActon implements ModelDriven<TUser>{
    static Logger logger = Logger.getLogger(UserAction.class);
    private static final long serialVersionUID = 1L;
    
    private UserService userService;
    private MemberRankService memberRankService;
    private TUser tUser = new TUser();
    private List<TRole> allRoles = new ArrayList<TRole>();
    private List<TMemberRank> allMemberRank = new ArrayList<TMemberRank>();
    private List<Integer> roleIds;
    private String authCode;
    private String forwardUrl;
    private String newPwd;
    private String newPwd2;
    /**
     * 进入用户注册页面
     * @return
     * @throws Exception 
     */
    @Override
    public String execute() throws Exception{
        logger.info("Entry register method!");
        return SUCCESS;
    }
    /**
     * 用户注册方法
     * @return
     * @throws Exception 
     */
    public String registerCheck() throws Exception{
        //判断验证码跟输入的验证码是否相同,不同跳转回注册的页面
        if(!checkAuthCode(this.getAuthCode())){
            addActionError("输入的验证码错误");
            return INPUT;
        }
        TMemberRank memberRank = memberRankService.getMemberRankById(TMemberRank.REGULAR_MEMBERS);
        tUser.setTMemberRank(memberRank);
        tUser.setPwd(EncodeUtils.encodePassword(tUser.getPwd()));   //保存用户数据密码为加密后的密码
        userService.saveUser(tUser);
        return SUCCESS;
    }
    /**
     * 进入用户登录页面
     * @return
     * @throws Exception 
     */
    public String login() throws Exception{
        logger.info("Entry login method!");
        return SUCCESS;
    }
    /**
     * 修改密码入口
     * @return
     * @throws Exception 
     */
    public String changepwd() throws Exception{
        logger.info("Entry changepwd method!");
        return SUCCESS;
    }
    
    public String ajaxChangPwd() throws Exception{
        logger.info("Entry ajaxChangPwd method!");
        TUser user = (TUser)session.get("user");
        user = userService.getUser(user.getUserId());
        JSONObject obj = new JSONObject();
        System.out.println(user.getNickName()+tUser.getPwd());
        System.out.println(EncodeUtils.isPasswordValid(user.getPwd(), tUser.getPwd()));
        if(EncodeUtils.isPasswordValid(user.getPwd(), tUser.getPwd())){
            if(getNewPwd().equals(getNewPwd2())){
                user.setPwd(EncodeUtils.encodePassword(getNewPwd()));
                userService.updateUser(user);
             
                obj.put("statusCode",200);
                obj.put("message", "修改密码成功!");
                obj.put("callbackType", "closeCurrent");
            }else{
                obj.put("statusCode",300);
                obj.put("message", "修改密码操作失败!");
            }
        }
        responseWriteJson(obj.toString());
        return null;
    }

    public String modifyUser() throws Exception{
        logger.info("Entry modifyUser method!"+request.getRequestURI()+"navTabId"+request.getQueryString());
        tUser = userService.getUser(tUser.getUserId());
        allRoles = userService.getAllRoles();
        allMemberRank = memberRankService.getAllMemberRanks();
        return SUCCESS;
    }
    
    public String ajaxUpdateUser() throws Exception{
        logger.info("Entry ajaxUpdateUser method!");
        Set<TRole> roles = new HashSet<TRole>();
        for (int roleId : roleIds) {
            System.out.println("----------"+roleId);
            TRole role = new TRole();
            role.setRoleId(roleId);
            roles.add(role);
        }
        TUser user = userService.getUser(tUser.getUserId());
        JSONObject result = new JSONObject();
         //如果用户为空
         if(user != null){
             user.setNickName(tUser.getNickName());
             user.setRealName(tUser.getRealName());
             user.setRoles(roles);
             //用户密码有改变的话
             if(tUser.getPwd() != null && !tUser.getPwd().equals(user.getPwd())){
                 //先加密用户密码再进行保存
                 user.setPwd(EncodeUtils.encodePassword(tUser.getPwd()));
             }
             userService.updateUser(user);
             
            result.put("statusCode", 200);
            result.put("message", "操作成功");
            System.out.println(request.getQueryString()+"-------"+super.getTabid());
            result.put("navTabId",super.getTabid());
            result.put("callbackType", "closeCurrent");
            super.responseWriteJson(result.toString());
         }else{
            result.put("statusCode",300);
            result.put("message", "修改用户信息失败!");
         }
        return null;
    }
    
     
    public String ajaxDeleteUser() throws Exception{
        logger.info("Entry ajaxUpdateUser method!"+request.getRequestURI()+"navTabId");
        //获取删除数据的ids
        String ids = request.getParameter("ids");
        logger.info("---------"+ids);
        JSONObject result = new JSONObject();
        
        result.put("statusCode", 200);
        result.put("message", "操作成功");
        System.out.println(request.getQueryString()+"-------"+super.getTabid());
        result.put("navTabId",super.getTabid());
        super.responseWriteJson(result.toString());
        return null;
    }
  
    /**
     * 用户退出系统
     * @return
     * @throws Exception 
     */
     public String logout() throws Exception{
        logger.info("Entry logout method!");
        session.invalidate();
        return SUCCESS;
    }
    
    /**
     * 用户登录处理方法
     * @return
     * @throws Exception 
     */
    public String loginCheck() throws Exception{
        logger.info("Entry loginCheck method!");
        
        //判断验证码跟输入的验证码是否相同,不同跳转回注册的页面
        System.out.println("---------"+getAuthCode());
        if(!checkAuthCode(this.getAuthCode())){
            addActionError("输入的验证码不相同");
            return INPUT;
        }
        TUser user = userService.getUserByUserName(this.tUser.getNickName());
        if(user== null){
            addActionError("用户名或密码不正确");
            return INPUT;
        }
        if(!EncodeUtils.isPasswordValid(user.getPwd(), tUser.getPwd())){
            addActionError("用户名或密码不正确");
            return INPUT;  
        }
      
        for (TRole r : user.getRoles()) {
            System.out.println(r.getRoleId());
        }
        SessionMap userMap = new SessionMap(request);
        userMap.put("user", user);
        setSession(userMap);
        //如果跳转的Url不为空就跳转到该URL
        if(getForwardUrl() != null && "".equals(getForwardUrl())){
            return "forwardUrl";
        }
        //有后台角色则跳转到后台管理页面,没就跳转到首页
        if(user.getRoles() != null && user.getRoles().size() > 0){
            return "admin";
        }else{
            return SUCCESS;
        }
    }
    
    /**
     * 用户名称唯一性检查
     * @return
     * @throws Exception  
     */
    public String userNameCheck() throws Exception{
        logger.info("Entry userNameCheck method!"+this.tUser.getNickName());
        String flag = "true";
        
        TUser user = userService.getUserByUserName(this.tUser.getNickName());
        if(user != null){
            flag = "false";
        }        
        responseWriteJson(flag);
        return null;
    }
    
    @Override
    public void validate() {
        if(tUser != null){
             if("".equals(tUser.getNickName())){
                addFieldError("nickName", "用户名不能为空");
            }
        }
    }
    /**
     * 检查验证码是否正确
     * @param authCode
     * @return 
     */
    public boolean checkAuthCode(String authCode){
        String rand = (String)this.session.get("rand");
        if(!rand.equals(authCode)){
            return false;
        }
        return true;
    }
    //public String
    @Override
    public TUser getModel() {
        return tUser;
    }

    /**
     * @return the authCode
     */
    public String getAuthCode() {
        return authCode;
    }

    /**
     * @param authCode the authCode to set
     */
    public void setAuthCode(String authCode) {
        this.authCode = authCode;
    }

    /**
     * @param userService the userService to set
     */
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * @param memberRankService the memberRankService to set
     */
    public void setMemberRankService(MemberRankService memberRankService) {
        this.memberRankService = memberRankService;
    }

    public String getForwardUrl() {
        return forwardUrl;
    }

    public void setForwardUrl(String forwardUrl) {
        this.forwardUrl = forwardUrl;
    }

    public String getNewPwd() {
        return newPwd;
    }

    public void setNewPwd(String newPwd) {
        this.newPwd = newPwd;
    }

    public String getNewPwd2() {
        return newPwd2;
    }

    public void setNewPwd2(String newPwd2) {
        this.newPwd2 = newPwd2;
    }

    public TUser gettUser() {
        return tUser;
    }

    public void settUser(TUser tUser) {
        this.tUser = tUser;
    }

    public List<TRole> getAllRoles() {
        return allRoles;
    }

    public void setAllRoles(List<TRole> allRoles) {
        this.allRoles = allRoles;
    }

    public List<Integer> getRoleIds() {
        return roleIds;
    }

    public void setRoleIds(List<Integer> roleIds) {
        this.roleIds = roleIds;
    }

    public List<TMemberRank> getAllMemberRank() {
        return allMemberRank;
    }

    public void setAllMemberRank(List<TMemberRank> allMemberRank) {
        this.allMemberRank = allMemberRank;
    }
    
}
